package com.hafu.dao;
import com.hafu.model.RuKuMain;
import com.hafu.util.DbUtil;
import com.hafu.util.StringUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class RuKuMainDao {
    public int addRuKuMain(RuKuMain ruKu,Connection conn)throws SQLException{
        String sql="insert into ruku_main(ruku_name,price,gys_name,rk_date)values(?,?,?,current_timestamp)";
        PreparedStatement preparedStatement=conn.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1,ruKu.getRukuName());
        preparedStatement.setBigDecimal(2,ruKu.getPrice());
        preparedStatement.setString(3,ruKu.getGysName());
        int i = preparedStatement.executeUpdate();
        if (i>0){
            ResultSet generatedKeys=preparedStatement.getGeneratedKeys();
            generatedKeys.next();
            return generatedKeys.getInt(1);
        }else{
            return -1;
        }
    }
    public ArrayList<RuKuMain> getRuKuMainByName(RuKuMain ruku){
        Connection conn=DbUtil.getConn();
        String sql = "select * from ruku_main";
        if (!StringUtil.isEmpty(ruku.getRukuName())){
            sql+=" where ruku_name like '%"+ruku.getRukuName()+"%'";
        }
        ArrayList<RuKuMain>list=new ArrayList<>();
        try {
            PreparedStatement preparedStatement=conn.prepareStatement(sql);
            ResultSet resultSet=preparedStatement.executeQuery();
            while (resultSet.next()){
                RuKuMain ruKuMain=new RuKuMain();
                ruKuMain.setId(resultSet.getInt("id"));
                ruKuMain.setRukuName(resultSet.getString("ruku_name"));
                ruKuMain.setPrice(resultSet.getBigDecimal("price"));
                ruKuMain.setGysName(resultSet.getString("gys_name"));
                ruKuMain.setRkDate(resultSet.getString("rk_date"));
                list.add(ruKuMain);
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }
        return list;
    }
    public Boolean updateRuKuMain(RuKuMain ruKuMain){
        Connection conn=DbUtil.getConn();
        String sql="update ruku_main set ruku_name=?where id=?";
        try {
            PreparedStatement preparedStatement=conn.prepareStatement(sql);
            preparedStatement.setString(1,ruKuMain.getRukuName());
            preparedStatement.setInt(2,ruKuMain.getId());
            int i = preparedStatement.executeUpdate();
            if (i>0){
                return true;
            }else return false;
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }
        return false;
    }
}
